import Cookies from 'js-cookie'

export default {
  cart: [
    // { ISBN, name, author, house, sellPrice, stock, cnt }
  ],
  add (book, cnt = 1) {
    this.loadFromCookie()
    this._add(book, cnt)
    this.dumpToCookie()
  },
  addlist (books) {
    this.loadFromCookie()
    for (let book of books) {
      this._add(book, 1)
    }
    this.dumpToCookie()
  },
  set (book, cnt) {
    this.loadFromCookie()
    this._set(book, cnt)
    this.dumpToCookie()
  },
  remove (book) {
    this.loadFromCookie()
    this._remove(book)
    this.dumpToCookie()
  },
  injectCookie (cart) {
    Cookies.set('ShoppingCart', this.cart, { expires: 7 })
  },
  dumpToCookie () {
    console.log(this.cart)
    Cookies.set('ShoppingCart', this.cart, { expires: 7 })
  },
  loadFromCookie () {
    this.cart = Cookies.getJSON('ShoppingCart') || []
    return this.cart
  },
  form () {
    this.loadFromCookie()
    let ct = []
    for (let item of this.cart) {
      ct.push({
        isbn: item.isbn,
        cnt: item.cnt
      })
    }
    return ct
  },
  clear () {
    Cookies.remove('ShoppingCart')
  },
  _push (book, cnt) {
    const { isbn, name, author, house, stock, sellPrice } = book
    this.cart.push({ isbn, name, author, house, stock, sellPrice, cnt })
  },
  _add (book, cnt) {
    for (let item of this.cart) {
      if (item.isbn === book.isbn) {
        item.cnt += cnt
        return true
      }
    }
    this._push(book, cnt)
  },
  _set (book, cnt) {
    for (let item of this.cart) {
      if (item.isbn === book.isbn) {
        item.cnt = cnt
        return true
      }
    }
    this._push(book, cnt)
  },
  _remove (book) {
    this.cart = this.cart.filter(item => item.isbn !== book.isbn)
  }
}
